<!-- 编辑弹窗 -->
<template>
    <div class="ele-body">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div v-show="form.swapNo!='' && form.swapNo!=null" style="width: 30%;color:var(--color-primary)" >调拨单号:{{ form.swapNo }}</div>
          </div>
        </div>      
        <el-row :gutter="24">
          <el-col :md="6" :sm="24">
            <el-form-item label="出库仓库:" prop="outWareHouseId">
              <el-select  v-model="form.outWareHouseId" filterable placeholder="请选择出库仓库" style="width:100%" @change="changeOutWarehouse">
                <el-option  v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="入库仓库:" prop="inWareHouseId">
              <el-select  v-model="form.inWareHouseId" filterable placeholder="请选择入库仓库" style="width:100%" @change="changeInWarehouse">
                <el-option  v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="制单日期:"  prop="swapDate">
              <el-date-picker v-model="form.swapDate" type="date" placeholder="请输入制单日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="制单人:" prop="operatorId">
              <el-select  v-model="form.operatorId" filterable placeholder="请选择制单人" style="width:100%" @change="selectoperate" >
                <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="调拨金额:"  >
              <el-input v-model="form.swapAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="18" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="1"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 8%;" >产品列表</div>
          <div style="width: 92%;display: flex;justify-content:start;" >
            <div style="width: 100%;color:var(--color-primary)" > 
                <el-button type="primary" class="ele-btn-icon" icon="el-icon-plus"  style="width: 10%;" @click="OpenProductList"  v-permission="'Inventory_Swaporder_ProductAdd'" >选择产品 </el-button>
              </div>
          </div>
        </div> 
        <el-table :data="form.items" ref="items"  :border="true" style="width: 100%"  :height="tableHeight" :full-height="tableFullHeight" show-summary :summary-method="getSummaries"  :cell-style="cellStyle">
          <el-table-column type="index" width="50" align="center" label="序号" />
          <el-table-column label="产品编号"  align="center" prop="productCode">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productCode }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="产品名称"  align="center" prop="productName">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productName }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="规格" align="center" prop="spc" >
            <template slot-scope="{ row }">
              <span>{{ row.spc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="unitDesc">
              <template slot-scope="{ row }">
                  <span>{{ row.unitDesc }}</span>
              </template>
          </el-table-column>
          <el-table-column label="调拨数量" align="center" width="100" prop="qty">
            <template slot-scope="{ row ,$index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.qty'" :rules="itemRules.qty" >
                <el-input  v-model="row.qty"  placeholder="请输入调拨数量" @change="setAmount(row,$index)"  @keyup.native="row.qty = row.qty.replace(/[^\d.]/g,'');
                  row.qty = row.qty.replace(/\.{2,}/g,'.');
                  row.qty = row.qty.replace(/^\./g,'');
                  row.qty = row.qty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.qty = row.qty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="可用数量" align="center" prop="stockQty">
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;"  >
                <el-input  v-model="row.stockQty"   disabled />
              </el-form-item>
            </template>
          </el-table-column>
           <el-table-column label="成本单价(￥)" align="center" width="150" prop="costPrice">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;"  >
                  <el-input  v-model="row.costPrice" disabled   prefix-icon="el-icon-_rmb"   />
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="金额" align="center" width="120" prop="amount">
            <template slot-scope="{ row }">
              <el-input  v-model="row.amount" disabled  prefix-icon="el-icon-_rmb"  />
            </template>
          </el-table-column>
          <!--<el-table-column label="供应商" align="center" width="150">
            <template slot-scope="{ row  }">
              <el-form-item label-width="10" style="margin-bottom:0;"  >
                <el-select  filterable disabled v-model="row.supplierId" placeholder="请选择供应商" class="ele-fluid" >
                  <el-option v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column label="行备注" align="center" width="250" >
            <template slot-scope="{ row }">
              <el-input  v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" v-if="this.btnIndex!=3">
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link  v-permission="'Inventory_Swaporder_ProductDel'"  icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card shadow="never"> </el-card>
    </el-form>
    <!-- <div slot="footer">
     
      <el-button type="primary" v-show="this.btnIndex!=3 && form.status!=5"  :loading="loading"  @click="save" >
        挂单
      </el-button>
      <el-button type="warning" v-show="this.btnIndex!=3 &&  form.status!=5" :loading="loading" @click="audit" >
        审核
      </el-button>
      <el-button type="danger" v-show="form.status==5"  @click="unAudit"   >
        反审核
      </el-button>
      <el-button @click="handleClose" >关闭</el-button>
    </div> -->
    <div  >
        <div class="ele-dailog-bottom" >
          <div class="left"  style="display: flex;width: 50%;">
          </div>
          <div class="right" style="display: flex;width: 32%;">
            <el-button type="primary" v-show="this.isUpdate!=3 && form.status!=5" :loading="loading"  @click="save" v-permission="'Inventory_Swaporder_Save'" >
              挂单
            </el-button>
            <el-button type="warning" v-show="this.isUpdate!=3 &&  form.status!=5" @click="audit" :loading="loadingAudit" v-permission="'Inventory_Swaporder_Audit'" >
              审核
            </el-button>
            <el-button type="danger" v-show="form.status==5"  @click="unAudit"  :loading="loadingUnAudit" v-permission="'Inventory_Swaporder_UnAudit'" >
              反审核
            </el-button>
            <el-button @click="handleClose" >关闭</el-button>
          </div>
        </div>
      </div>
     <!-- 编辑弹窗 -->
     <productchooseList :data="current" :visible.sync="showProductList"  @callback="reloadItemList"/>
    </div>
  </template>
  <script>
   
   import productchooseList from '../components/productchoose-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { QueryThirdcompanyType } from '@/api/enummanger';
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier, QuerySupplierByType} from '@/api/basicdatamanager/supplier';
   import { AddSwaporder,UpdateSwaporder,QuerySwaporderById,AuitSwaporder,AnitSwaporder } from '@/api/inventory/swaporder';
   import { removePageTab, reloadPageTab,setPageTabTitle } from '@/utils/page-tab-util';

    export default {
      name: 'SwaporderEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {productchooseList},
      data() {
        return {
          // 表单数据
          form: {createUser:'',createDate:'',items:[]},
          // 表单验证规则
          rules: {
            outWareHouseId: [{required: true,message: '请选择出库仓库',trigger: 'blur'}],
            inWareHouseId: [{required: true,message: '请选择入库仓库',trigger: 'blur'}],
            swapDate: [{required: true,message: '请选择制单日期',trigger: 'blur'}],
            operatorId: [{required: true,message: '请选择制单人',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            costPrice: [{required: true,message: '请输入成本单价',trigger: 'blur'}],
          },
          fixedHeight:true,
          current:null,
          isShow:false,
          // 提交状态
          loading: false,
          loadingAudit: false,
          loadingUnAudit: false,
          // 是否是修改
          isUpdate: 1,
          swaporderId:'',
          showProductList:false,
          defaultDate:new Date(),
          hbDatas:[],
          accountDatas:[],
          supplierDatas:[],
          wareHouseDatas:[],
          QGCompanyDatas:[],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {

          var fh = this.fixedHeight ? 'calc(100vh - 480px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 380px)' : null;
          return fh;
        },
      },
    
      //初始化数据
      mounted(){
        if(this.isUpdate == 2 || this.isUpdate == 3){
          this.setData(this.swaporderId);
        }else if(this.isUpdate == 1){
          this.$refs['form'].clearValidate();
          this.form={items:[]};
          this.isUpdate = 1;
          let currentUser = getUser();
          this.$set(this.form,'swapDate',this.defaultDate);
          this.$set(this.form,'operatorId',currentUser.accountId);
          this.$set(this.form,'operatorName',currentUser.accountName);
        }
      },
      created(){
        this.initData();
        this.isUpdate = this.$route.query.isUpdate;
        this.swaporderId = this.$route.query.swaporderId;
        if(this.isUpdate == 1)  setPageTabTitle('添加调拨单');
        if(this.isUpdate == 2)  setPageTabTitle('修改调拨单');
        if(this.isUpdate == 3)  setPageTabTitle('查看调拨单');
      },
      methods: {

        /* 初始化数据 */
        initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });
        },

        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}


            let qty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.qty?cur.qty:0) },0);
            let useqty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.stockQty?cur.stockQty:0) },0);

            if(qty >= useqty){
              this.$message.error('调拨数量不能大于可用数量');
              return;
            }

            this.loading = true;
            const saveOrUpdate = this.isUpdate ==2 ? UpdateSwaporder : AddSwaporder;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible();
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        audit(){
          //校验必填信息
          this.$refs['form'].validate((valid) => {
          if (!valid) {return false;}

          if(this.form.items==null || this.form.items==undefined || this.form.items.length==0){
            this.$message.info('产品列表不能为空');
            return;
          }

          let qty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.qty?cur.qty:0) },0);
          let useqty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.stockQty?cur.stockQty:0) },0);

          if(qty >= useqty){
            this.$message.error('调拨数量不能大于可用数量');
            return;
          }

          this.loadingAudit = true;
          AuitSwaporder(this.form)
            .then((msg) => {
              this.loadingAudit = false;
              this.$message.success(msg);
              this.updateVisible();
            })
            .catch((e) => {
              this.loadingAudit = false;
              this.$message.error(e.message);
            });
          });
        },

        unAudit(){
          this.loadingUnAudit = true;
          AnitSwaporder(this.form.id)
            .then((msg) => {
              this.loadingUnAudit = false;
              this.$message.success(msg);
              this.updateVisible();
            })
            .catch((e) => {
              this.loadingUnAudit = false;
              this.$message.error(e.message);
            });
        },

        setData(id){
          QuerySwaporderById(id)
            .then((res) => {
              this.form = res; 

              this.$nextTick(() => {
                this.$refs.items.doLayout();
              });
          });
        },

        selectoperate(val){
          let acc = this.accountDatas.find((v)=>{ return v.id == val });
          if(acc){
            this.form.operatorName = acc.name;
          }
        },

        OpenProductList(){
          if(this.form.outWareHouseId){
            this.showProductList =true;
            this.current = this.form;
          }else{
            this.$message.info("请选择出库仓库")
          }
        },

        changeOutWarehouse(val){

         if(this.form.inWareHouseId == val){
          this.$message.info('出库与入库不能为同一仓库');
          this.form.outWareHouseId = '';
          return;
         } 
        },

        changeInWarehouse(val){
          if(this.form.outWareHouseId == val){
            this.$message.info('出库与入库不能为同一仓库');
            this.form.inWareHouseId= '';
            return;
          } 
        },

        reloadItemList(orderData){

          orderData.map((item)=>{

            let product = this.form.items.find((d)=>{
              return d.productId == item.productId
            })
            if(product){
              // this.$message.info('当前选择的产品'+product.productName+'在列表中已经存在');
              product.stockQty = item.useQty;
              return;
            }else{

              this.form.items.push({
                supplierId:item.supplierId,
                stockId:item.id,
                unitId:item.unitId,
                qty:0,
                amount:0,
                costPrice:item.costPrice,
                stockQty:item.useQty,
                swapId:this.form.id,
                productId:item.productId,
                supplierDesc:item.supplierDesc,
                productCode:item.productCode,
                productName:item.productName,
                spc:item.spc,
                unitDesc:item.unitDesc,
              })
            }
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });

          this.setPurAmountTotal();
        },

        //设置金额
        setAmount(row,index){
          if(row.qty>row.stockQty){
            this.$message.error("调拨数量不能大于库存数量");
            return ;
          }else{
           
            if(row.costPrice && row.qty!=null && row.qty!=undefined&& row.qty!='' ){
              let rq = parseFloat(row.qty);
              let cp = parseFloat(row.costPrice);
              this.$refs.items.data[index].amount = (rq * cp).toFixed(2);
              this.setPurAmountTotal();
            }
          }
        },


        //设置入库金额
        setPurAmountTotal(){
          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){
            let qty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.qty) },0);
            let amount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.amount) },0);
            this.$set(this.form,'qtyTotal',qty.toFixed(2));
            this.$set(this.form,'swapAmount',amount.toFixed(4))
          }
        },


        /* 删除 */
        remove(_row, index) {
          // this.form.items.splice(index, 1);
          this.form.items = this.form.items.filter((c)=>{return c.productCode !=_row.productCode && c.productName != _row.productName});
          this.setPurAmountTotal();
        },
     
        /* 更新visible */
        updateVisible() {
          removePageTab({ key: this.$route.path });
          reloadPageTab({ fullPath: '/invoicingmanager/swapordermanager' });
        },

        handleClose() {
          removePageTab({ key: this.$route.path });
          this.$router.push('/invoicingmanager/swapordermanager');
        },

        /* 合计 */
        getSummaries(param){
          const sums = [];
          sums[0] = '合计' ;
          const { columns, data } = param;
          columns.forEach((column, index) => {
            if(index ==5){
              sums[index] = Number(this.form.qtyTotal).toFixed(2);
            }else if(index ==8){
              sums[index] = Number(this.form.swapAmount).toFixed(4);
            }
          });

          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });
          return sums;
        },

        /* 样式 */
        cellStyle(param){
          const { row, column, rowIndex, columnIndex } = param;
          if(columnIndex==5||columnIndex==6||columnIndex==8){
            return{
              color:'var(--color-primary)'
            }
          }
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={items:[]};
              this.isUpdate = false;
              let currentUser = getUser();
              this.$set(this.form,'swapDate',this.defaultDate);
              this.$set(this.form,'operatorId',currentUser.accountId);
              this.$set(this.form,'operatorName',currentUser.accountName);
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {};
              let currentUser = getUser();
              this.form.operatorId = currentUser.accountId;
              this.form.swapDate = this.defaultDate;
          }
        }
      }
    };
  </script>
  <style lang="scss" scoped>
  /*总计字体颜色*/
  ::v-deep .el-table__footer-wrapper tbody td {
     color: var(--color-primary);
     cursor: pointer;
   }
 </style>